const db = wx.cloud.database()
const _ = db.command
const $ = _.aggregate
const app = getApp()
let count = 0
Page({
  data: {
    date: app._getNianYuiRi(),
    time: '上午',
    areaList: [],
    seatList: [],
    seatNum: 0
  },
  onLoad() {
    this.getFloorList()
    let hour = new Date().getHours()
    console.info(hour)
    this.setData({
      time: hour < 12 ? '上午' : '下午'
    })
  },
  // 获取每个教学楼的教室情况
  getFloorList() {
    count = 0
    let _this = this
    wx.showLoading()
    console.log('$floor')
    db.collection('venue').aggregate()
      .group({
        _id: '$floor',
        num: $.addToSet('$region')
      })
      .sort({
        _id: 1
      })
      .end()
      .then(res => {
        console.log('教室数据', res)
        _this.setData({
          list: res.list
        })
        res.list.forEach((l) => {
          _this.getAreaList(l._id)
        })
      })
  },
  //去单个教学楼预约
  goDetail(e) {
    let item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/reserve/reserve?floor=' + item._id,
    })
  },

  // 选择日期
  bindDateChange: function (e) {
    let _this = this
    if (app._getNianYuiRi() > e.detail.value) {
      _this.setData({
        list: []
      })
      wx.showModal({
        title: "提示",
        content: "只可以选择今日或者以后的日期，之前的日期没法选择",
        showCancel: false
      })
      return
    } else {
      this.setData({
        date: e.detail.value,
        areaList: [],
        seatList: [],
        time: '上午'
      }, () => {
        _this.getFloorList()
      })

    }
  },

  /**
   * 选择上午/下午
   */
  clickTime() {
    let _this = this
    let hour = new Date().getHours()
    console.info(hour)
    let tempList = (hour < 12 || app._getNianYuiRi() < this.data.date) ? ['上午', '下午'] : ['下午']
    wx.showActionSheet({
      itemList: tempList,
      success(res) {
        _this.setData({
          time: tempList[res.tapIndex],
          areaList: [],
          seatList: []
        }, () => {
          _this.getFloorList()
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  /**
   * 获取区域数据
   */
  getAreaList(floor) {
    let _this = this
    db.collection('venue').aggregate()
      .match({
        floor,
        timeList: _.not(_.eq(this.data.date + '-' + this.data.time))
      })
      .group({
        _id: '$region',
        num: $.sum(1),
      })
      .sort({
        _id: 1
      })
      .end()
      .then(res => {
        const areaList = JSON.parse(JSON.stringify(_this.data.areaList))
        const tempList = res.list
        tempList.map((a) => {
          a.floor = floor
          areaList.push(a)
        })
        _this.setData({
          areaList
        })
        count += 1
        if (count == _this.data.list.length) {
          areaList.map((a) => {
            _this.getSeatList(a.floor, a._id)
          })
        }
        console.log(floor + '可预定教室列表', areaList, "========" + (count))
      })

  },

  /**
   * 获取座位数据
   */
  getSeatList(floor, region) {
    const date = this.data.date + '-' + this.data.time
    const seatList = this.data.seatList
    const _this = this
    db.collection('venue').where({
        floor,
        region,
        timeList: _.not(_.eq(date))
      }).get()
      .then(res => {
        // console.log('可预约的座位', res)
        wx.hideLoading()
        const tempList = res.data
        tempList.map((a) => {
          seatList.push(a)
        })
        _this.setData({
          seatList
        })
        console.log('可预约的座位', seatList)
      })
  },

  // 选中的点击事件
  clickChoose(e) {
    let seatNum = 0
    let id = e.currentTarget.dataset.id
    let list = this.data.seatList
    list.forEach(item => {
      if (item._id == id) {
        item.selected = !item.selected
      }
      if (item.selected) {
        seatNum += 1
      }
    })
    if (seatNum > 2) {
      wx.showToast({
        icon: "error",
        title: '最多2个座位',
      })
      return
    }
    this.setData({
      seatList: list,
      seatNum
    })
  },

  //点击预约
  pay() {
    if (this.data.seatNum <= 0) {
      wx.showToast({
        icon: "error",
        title: '请选择座位',
      })
      return
    }
    if (this.data.seatNum > 2) {
      wx.showToast({
        icon: "error",
        title: '最多2个座位',
      })
      return
    }
    wx.showModal({
      title: "提示",
      content: "预约座位请慎重选择，如果预约后不去使用，会影响个人信用",
      confirmText: '确定预约',
      success: res => {
        if (res.confirm) {
          this.addOrder()
        }
      }
    })

  },
  //添加预定
  addOrder() {
    let dataList = []
    let proArr = []
    let user = app.globalData.userInfo
    let date = this.data.date + '-' + this.data.time
    let _this = this
    this.data.seatList.forEach(item => {
      if (item.selected) {
        dataList.push(item._id)
        let pro = db.collection('order').add({
          data: {
            venueFloor: item.floor,
            venueRegion: item.region,
            venueId: item._id,
            seat: item.seat,
            date: date,
            name: user.name,
            phone: user.phone,
            type: user.type,
            department: user.department,
            status: '待使用'
          }
        })
        proArr.push(pro)
      }
    })
    Promise.all(proArr)
      .then(res => {
        console.log('添加预定成功', res)
        // 全部预定添加成功以后，去改变教室状态
        wx.cloud.callFunction({
          name: 'venue',
          data: {
            action: 'reserve',
            list: dataList,
            date: date
          }
        }).then(res => {
          console.log('修改教室状态结果', res)
          wx.showToast({
            title: '预定成功',
          })
          _this.setData({
            areaList: [],
            seatList: []
          }, () => {
            setTimeout(() => {
              _this.getFloorList()
            }, 1000)
          })

        })
      })
      .catch(res => {
        console.log('添加预定失败', res)
      })
  }
})